from django.db.models import Sum

import xadmin
from operations.models import OperationList, OperationReport

from utils.constants import PAGE_SIZE
from utils.tools import set_invalid, set_valid


class OperationListAdmin(object):
    """ 运营 """
    list_display = (
        'created_at', 'is_valid', 'operation_client', 'operation_media', 'product', 'sales', 'account_name',
        'consume', 'client_rebate', 'consume_cash', 'conversions', 'cost', 'copy', 'check', 'operation',
        'media_rebate', 'profit', 'remark'
    )
    list_filter = ('created_at', 'is_valid', 'operation_client', 'operation_media', 'product',
                   'sales', 'account_name', 'operation')
    search_fields = ('sn', 'operation_client__name', 'operation_media__name',
                     'product', 'sales', 'account_name', 'operation')
    list_per_page = PAGE_SIZE  # 分页的页数
    readonly_fields = ('sn', 'profit', 'consume_cash', 'cost')  # 不可编辑，在界面上可见
    exclude = ('is_valid',)  # 排除，在页面上无法显示
    model_icon = 'fa fa-mouse-pointer'
    show_bookmarks = False  # 关闭书签功能
    reversion_enable = True

    # 可以使用聚合函数
    aggregate_fields = {'consume': 'sum', 'consume_cash': 'sum', 'profit': 'sum'}
    list_editable = ('consume', 'client_rebate', 'conversions', 'media_rebate')

    def queryset(self):
        """函数作用：使当前登录的用户只能看到自己负责的设备"""
        qs = super().queryset()
        if self.request.user.is_superuser or self.request.user.is_leader:
            return qs
        return qs.filter(operation_id=self.request.user)

    def instance_forms(self):
        """ 添加订单时，自动添加当前用户的id """
        super().instance_forms()
        # 判断是否为新建操作，新建操作才会设置user_id的默认值
        if not self.org_obj:
            self.form_obj.initial['operation_id'] = self.request.user.id


class OperationReportAdmin(object):
    object_list_template = 'operation_report.html'
    list_display = (
        'created_at', 'is_valid', 'operation_client', 'operation_media', 'product', 'sales', 'account_name',
        'consume', 'client_rebate', 'consume_cash', 'conversions', 'cost', 'copy', 'check', 'operation',
        'media_rebate', 'profit', 'remark'
    )
    list_filter = ('created_at', 'is_valid', 'operation_client', 'operation_media', 'product',
                   'sales', 'account_name', 'operation')
    search_fields = ('sn', 'operation_client__name', 'operation_media__name',
                     'product', 'sales', 'account_name', 'operation')
    list_per_page = PAGE_SIZE  # 分页的页数
    readonly_fields = ('sn', 'profit', 'consume_cash', 'cost')  # 不可编辑，在界面上可见
    exclude = ('is_valid',)  # 排除，在页面上无法显示
    model_icon = 'fa fa-bar-chart-o'
    show_bookmarks = False  # 关闭书签功能
    actions = [set_invalid, set_valid]  # 批量审核/反审核
    list_editable = ('consume', 'client_rebate', 'conversions', 'media_rebate')

    def get_context(self):
        """ 重写方法，把要展示的数据更新到context """
        context = super().get_context()

        # 从数据库查出的结果集
        invoice_all = OperationList.objects.all()

        # 查询结果集，使总数能随着筛选进行改变
        filter_conditions = {}
        for k, v in self.request.GET.items():
            if '_p_' in k:
                key = k.split('_p_')
                filter_conditions[key[1]] = v

        # 消耗
        sum_consume = OperationList.objects.filter(is_valid=True) \
            .filter(**filter_conditions) \
            .aggregate(consume=Sum('consume'))

        # 消耗现金
        sum_consume_cash = OperationList.objects.filter(is_valid=True)\
            .filter(**filter_conditions)\
            .aggregate(consume_cash=Sum('consume_cash'))
        # 利润
        sum_profit = OperationList.objects.filter(is_valid=True)\
            .filter(**filter_conditions)\
            .aggregate(profit=Sum('profit'))

        context.update(
            {
                'sum_consume': sum_consume,
                'sum_consume_cash': sum_consume_cash,
                'sum_profit': sum_profit,
            }
        )

        return context


xadmin.site.register(OperationList, OperationListAdmin)
xadmin.site.register(OperationReport, OperationReportAdmin)

